package com.chinawayltd.ews.sample.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * @program: g7ews4java-sample
 * @description:
 * @author: xiazj
 * @create: 2018-04-13 11:15
 **/
public class BeanUtils extends org.springframework.beans.BeanUtils{
    private final static  String[] NOT_COPY_FIELD = {"id", "createTime", "updateTime"};

    /**
     * 获取到对象中属性为null的属性名
     * @param source 要拷贝的对象
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 拷贝非空对象属性值
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * 拷贝数据库表映射对象，默认不拷贝id、createTime、updateTime
     * @param source
     * @param target
     */
    public static void copyDOProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target, NOT_COPY_FIELD);
    }
    
    /**
     * 拷贝数据库表映射对象，默认不拷贝id、createTime、updateTime
     * @param source
     * @param target
     * @param ignoreProperties 不过滤的属性名称数组
     */
    public static void copyDOProperties(Object source, Object target, String... ignoreProperties) {
    	if(ignoreProperties != null && ignoreProperties.length > 0){
    		List<String> names = Arrays.asList(ignoreProperties);
    		names.addAll(Arrays.asList(NOT_COPY_FIELD));
    		ignoreProperties = names.toArray(ignoreProperties);
    	}
        BeanUtils.copyProperties(source, target, NOT_COPY_FIELD);
    }

}
